# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def HasSubtree(self, pRoot1, pRoot2):
        # write code here
        def isSubclass(pRoot1, pRoot2):
            '''
            该算法只要跑到pRoot2为空时就会返回True
            :param pRoot1:
            :param pRoot2:
            :return:
            '''
            if not pRoot2:
                # 如果pRoot2是空的，那么说明pRoot2的子树没有了，那么就相同
                return True
            if not pRoot1:
                # pRoot2不为空的前提下，pRoot1为空，那么必然不相同
                return False
            if pRoot1.val == pRoot2.val:
                # 如果节点相同，那么判断左右两个子树是否相同
                return isSubclass(pRoot1.left, pRoot2.left) and isSubclass(pRoot1.right, pRoot2.right)
            else:
                return False
        if not pRoot2 or not pRoot1:
            return False
        flag = False
        if pRoot1.val == pRoot2.val:
            flag = isSubclass(pRoot1.left, pRoot2.left) and isSubclass(pRoot1.right, pRoot2.right)# 如果当前节点的值相同，那么就检测该点的两个子树是否依旧相同
        if not flag:
            # flag不为True时，判断左右两个节点是否存在返回真的情况
            flag = self.HasSubtree(pRoot1.left, pRoot2) or self.HasSubtree(pRoot1.right, pRoot2)
        return flag
